package cn.mengfly.fxtest.app;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Pagination;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Mengfly
 * @date 2021/5/28 13:37
 */
public class SlidShowApp extends Application {

    private final List<File> imageList = new ArrayList<>();
    private final DirectoryChooser directoryChooser = new DirectoryChooser();

    @Override
    public void start(Stage primaryStage) {
        directoryChooser.setTitle("Select Image Directory");

        Pagination pagination = new Pagination(1);
        pagination.setPadding(new Insets(10));
        pagination.setPageFactory(this::getImageView);
        VBox.setVgrow(pagination, Priority.ALWAYS);

        HBox hBox = new HBox();
        hBox.setAlignment(Pos.CENTER);
        hBox.setSpacing(10);

        TextField textField = new TextField();
        Button button = new Button("Select dir");
        button.setOnAction(event -> {
            File file = directoryChooser.showDialog(primaryStage);
            if (file == null || !file.exists()) {
                return;
            }
            textField.setText(file.getAbsolutePath());
            File[] files = file.listFiles((dir, name) -> name.endsWith(".jpg") || name.endsWith(".png"));
            if (files == null) {
                return;
            }
            pagination.setPageCount(0);
            imageList.clear();
            imageList.addAll(Arrays.asList(files));
            pagination.setPageCount(imageList.size());
        });
        hBox.getChildren().addAll(textField, button);

        VBox root = new VBox();
        root.setSpacing(10);
        root.setPadding(new Insets(10));
        root.getChildren().addAll(hBox, pagination);

        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.setTitle("SlidShowApp");
        primaryStage.show();
    }

    public ImageView getImageView(int index) {

        ImageView imageView = new ImageView();
        imageView.setFitWidth(600);
        imageView.setFitHeight(600);
        imageView.setSmooth(true);
        imageView.setPreserveRatio(true);
        if (imageList.isEmpty()) {
            return imageView;
        }
        imageView.setImage(new Image(imageList.get(index).toURI().toString()));
        return imageView;
    }


}
